<?php
namespace app\api\controller\product;

use app\api\controller\Api;
use app\common\product\model\CustomerCfg;
use app\common\product\validate\CustomerCfgValidate;

class Customer extends Api
{
    // 规则列表
    public function index()
    {
        $post = $this->request->post();
        if (empty($post['category_id'])) return error([], "参数错误");

        $where = [];
        $where[] = ['category_id', '=', $post['category_id']];
        $model = new CustomerCfg();
        $list = $model->where($where)->order('sort,id desc')->select();

        $result['list'] = $list;

        return success($result);
    }

    // 读取规则详情
    public function read()
    {
        $post = $this->request->post();
        if (empty($post['id'])) return error([], '参数错误');

        $where = [];
        $where[] = ['id', '=', $post['id']];
        $model = new CustomerCfg();
        $row = $model->where($where)->find();

        if ($row) {
            $result['detail'] = $row;
            return success($result, '获取数据成功');
        } else {
            return error([], '获取数据失败');
        }
    }

    // 创建规则
    public function create()
    {
        $post = $this->request->post();
        // 创建的时候清除干扰的信息
        unset($post['id']);
        $validate = new CustomerCfgValidate();
        if (!$validate->check($post)) return error([], $validate->getError());

        $user = $this->request->user;
        $post['operator_id'] = $user['id'];
        $model = new CustomerCfg();
        $saveRs = $model->save($post);

        if ($saveRs) {
            return success([], '保存成功');
        } else {
            return error([], '保存失败');
        }
    }

    // 编辑规则权限
    public function save()
    {
        $post = $this->request->post();

        $validate = new CustomerCfgValidate();
        if (!$validate->check($post)) return error([], $validate->getError());

        $where = [];
        $where[] = ['id', '=', $post['id']];
        $model = new CustomerCfg();
        $row = $model->where($where)->find();

        $user = $this->request->user;
        $post['operator_id'] = $user['id'];
        $saveRs = $row->save($post);
        if ($saveRs) {
            return success([], '保存成功');
        } else {
            return error([], '保存失败');
        }
    }

    // 删除指定规则
    public function delete()
    {
        $post = $this->request->post();
        if (!isset($post['id'])) return error([], '参数错误');

        $where = [];
        $where[] = ['id', '=', $post['id']];
        $model = new CustomerCfg();
        $row = $model->where($where)->find();
        if (empty($row)) return error([], '规则不存在');

        $rs = $row->delete();
        if ($rs) {
            return success([], '删除成功');
        } else {
            return error([], '删除失败');
        }
    }
}